<template>
  <view class="home">
    <view class="mqttTest">
      <button @click="connect" type="primary">连接 MQTT</button>
      <!-- <button @click="disconnectMqtt" type="default">断开 MQTT</button> -->
      <button @click="publishMessage" type="primary">发布消息</button>
	   <button @click="publishMessage" type="primary">发布消息</button>
	    <button @click="publishMessage" type="primary">发布消息</button>
		 <button @click="publishMessage" type="primary">发布消息</button>
    </view>
  </view>
</template>

<script>
import { v4 } from 'uuid';
import { MQTT_IP, MQTT_OPTIONS } from '@/utils/mqtt.js';
var mqtt = require('mqtt/dist/mqtt.js');
var client;

export default {
  data() {
    return {
      topic: 'testtopic/1',
      message: 'Hello MQTT!' ,// 发布的消息
	  topic2: 'testtopic/2',
    };
  },
  mounted() {
      this.connect() // 连接
  },
  methods: {
    connect() {
      MQTT_OPTIONS.clientId = v4();
      var that = this;

      // 根据运行环境选择连接协议
      // #ifdef H5
      client = mqtt.connect('ws://' + MQTT_IP, MQTT_OPTIONS);
      // #endif
      // #ifdef MP-WEIXIN||APP-PLUS
      client = mqtt.connect('wx://' + MQTT_IP, MQTT_OPTIONS);
      // #endif

      // 监听连接成功事件
      client.on('connect', function() {
        console.log('连接成功');
        client.subscribe(that.topic, function(err) {
          if (!err) {
            console.log('订阅成功');
          } else {
            console.error('订阅失败:', err);
          }
        });
      });

      // 监听重连事件
      client.on('reconnect', function(error) {
        console.log('正在重连...', error);
      });

      // 监听连接错误事件
      client.on('error', function(error) {
        console.error('连接失败:', error);
      });

      // 监听连接断开事件
      client.on('end', function() {
        console.log('连接断开');
      });

      // 监听接收到消息事件
      client.on('message', function(topic, message) {
        console.log('接收推送信息：', message.toString());
      });
    },

    disconnectMqtt() {
      if (client) {
        console.log('尝试断开 MQTT 连接');
        client.end(true, () => {
          console.log('MQTT 连接已断开');
        });
      } else {
        console.log('客户端未连接或已断开');
      }
    },

    publishMessage() {
      if (client && client.connected) {
        console.log('发布消息到主题', this.topic2);
        client.publish(this.topic2, this.message, (err) => {
          if (err) {
            console.error('发布失败:', err);
          } else {
            console.log('消息已发布');
          }
        });
      } else {
        console.log('MQTT 客户端未连接');
      }
    }
  }
};
</script>

<style lang="scss">
  .mqttTest {
    button {
      margin: 20rpx 10rpx;
      height: 100rpx;
      color: #F7F8FA;
      background-color: #4CAF50;
      &:disabled {
        background-color: #BDBDBD; // 禁用时按钮颜色
      }
    }
  }
</style>
